#include "facedetector.h"
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <QDebug>
FaceDetector::FaceDetector(QObject *parent) :
    QObject(parent)
{
}
bool FaceDetector::Init()
{
    static bool inited=false;
    if(inited)
        return true;
    qDebug()<<"init:"<<inited;
    bool ret=mFaceCascade.load("D:\\Project\\LearningOpencv\\TestObjectDetect\\haarcascade_frontalface_alt.xml");
    if(ret==false)
        return false;
    ret=mEyeCascade.load("D:\\Project\\LearningOpencv\\TestObjectDetect\\haarcascade_eye_tree_eyeglasses.xml");
    if(ret==false)
        return false;
    inited=true;
    return true;
}

void FaceDetector::DoDetect(QImage& image)
{
    cv::Mat mat;
    if(image.format()==QImage::Format_RGB888)
    {
        cv::Mat src=cv::Mat(cv::Size(image.width(),image.height()),CV_8UC(3),image.bits());
        cv::cvtColor(src,mat,CV_RGB2GRAY);
    }
    else if(image.format()==QImage::Format_RGB32)
    {
        cv::Mat src=cv::Mat(cv::Size(image.width(),image.height()),CV_8UC(4),image.bits());
        cv::cvtColor(src,mat,CV_RGBA2GRAY);
    }
    else if(image.format()==QImage::Format_Indexed8)
        mat=cv::Mat(cv::Size(image.width(),image.height()),CV_8UC(1),image.bits());
    else
    {
        qDebug()<<image.format()<<" not support";
        return;
    }
    std::vector<cv::Rect> faces;
    mFaceCascade.detectMultiScale(mat,faces,1.1,2,0|CV_HAAR_SCALE_IMAGE,cv::Size(30,30));

    mFaces.clear();
    for(int i=0;i<faces.size();i++)
    {
        cv::Rect face=faces.at(i);
        mFaces.append(QRect(face.x,face.y,face.width,face.height));
    }
    qDebug()<<"Faces:"<<mFaces.size();
}
void FaceDetector::DoDetect(cv::Mat frame)
{
    cv::Mat mat;

    std::vector<cv::Rect> faces;
    cv::cvtColor(frame,mat,CV_BGR2GRAY);

    qint64 t1=cv::getTickCount();
    mFaceCascade.detectMultiScale(mat,faces,1.1,2,0|CV_HAAR_SCALE_IMAGE,cv::Size(80,80));
    qint64 t2=cv::getTickCount();
    qDebug()<<"time:"<<(float(t2-t1))/cv::getTickFrequency();
    mFaces.clear();
    for(int i=0;i<faces.size();i++)
    {
        cv::Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 );
        cv::ellipse( frame, center, cv::Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, cv::Scalar( 255, 0, 255 ), 4, 8, 0 );
    }
}
